package com.ynny.usermanager.controller;

import com.ynny.usermanager.dao.UserDao;
import com.ynny.usermanager.entity.R;
import com.ynny.usermanager.entity.User;
import com.ynny.usermanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping ("/user")
public class UserController {

    @Autowired
    UserDao userDao;

    @Autowired
    UserService userService;

    @GetMapping("/{id}")
    public R get(@PathVariable(name = "id") Integer id){

        System.out.println("获取的id：" + id);

        User user = userDao.selectUserById(id);
        if (user == null) {
            new R(201,"查询无果",null);
        }

        return R.ok(user);
    }


    //查询所有用户信息
    @RequestMapping("/list")
    public R list(){

        //模拟集合数据
        List<User> users = userDao.selectAllUsers();

        return R.ok(users);

    }

    @PostMapping("/add")
    public R add(@RequestBody User user){


        System.out.println("request:----》" + user);
        //添加用户 判断用户名是否存在
        //
//        userDao.selectUserByUserName();

//        int i = userDao.addUser(user);

        int i = userService.saveUser(user);

        if (i == 200 ){
            return R.ok(user.getUsername());
        } else if (i == 202) {
            return new R(202,"用户名已经存在",null);
        }
        return R.ok(null);

    }


    @DeleteMapping("/{id}")
    public R delete(@PathVariable(name = "id") Integer id){

        System.out.println("删除的用户id:" + id);
        int i = userDao.deleteUser(id);

        return R.ok(null);

    }


    @PutMapping
    public R update(@RequestBody User user){

        System.out.println("需要修改的用户为: " + user);

        int i = userDao.updateUser(user);

        if (i > 0 ){
            return R.ok(user.getUsername());
        }

        return R.ok(null);

    }

}
